var amount;
$(function () {
    initEvent();
    getProductList();
    if (common.get('order_price')) {
        $('#b_borrow_amount').val(common.get('order_price')).attr('readonly', true);
    }
});

function initEvent() {
    $("#submitMsg").off('click').on('click', function () {
        submitMsg();
    });
}

function getProductList(){
    var datas = {
        interface:'product@productList',
        fundType:'1'
    };
    var html = '<option value="">请选择</option>';
    common.ajax({
        data: datas,
        success: function (data) {
            if (data.status == '2000') {
                if(data.result.partner_k12 == '2'){
                    $('#is_partner_k12').val('2');
                    getTplHtml('studentform',$('#parentInfo'));
                }
                html += common.formatTemplate(data.result.productList,'<option value="{p_name}">{p_name_text}</option>',true);
                $('#productList').html(html);

                // console.log(data.result);
                if(data.result.p_name){
                    $("#productList").val(data.result.p_name);
                    if(data.result.set_amount){
                        $("#b_borrow_amount").val(data.result.set_amount);
                        amount = data.result.set_amount;
                    }

                    getPeriodList();
                }

            } else if (data.status == '5000') {
                falert(data.msg, '/user/mechanism');
            }
        }
    });  
}

function getPeriodList(){
    var p_name = $('#productList').val();
    if(p_name == ''){
        falert('请选择正确的课程名称');
        return false;
    }
    $('#p_id,#b_period').val('');
    if(!common.get('order_price')){
        $('#b_borrow_amount').val('');
    }
    $('#fundList').html('');
    $('#selectFund').hide();
    var datas = {
        interface:'product@periodList',
        p_name:p_name
    };
    var html = '';
    common.ajax({
        data: datas,
        success: function (data) {
            if (data.status == '2000') {
                if(data.result.length>1){
                    var str;
                    if(amount){
                        str = 'amt="'+amount+'"';
                    }else{
                        str = 'amt="{p_set_amount}"';
                    }
                    html += common.formatTemplate(data.result,'<div class="fl radius10" value="{p_period}" p_id="{p_id}" '+str+' amount_fixed="{p_amount_fixed}" p_min_amt="{p_min_amt}" p_max_amt="{p_max_amt}" onclick="xzSelected(this,\'periodList\')">{p_period}月</div>',true);
                    $('#periodList').html(html);
                }else{
                    //如果是修改过的金额，传过来，这里需要把账单金额修改了。
                    var str;
                    if(amount){
                        str = 'amt="'+amount+'"';
                    }else{
                        str = 'amt="{p_set_amount}"';
                    }

                    html = common.formatTemplate(data.result,'<div class="selectedNumber fl radius10" value="{p_period}" p_id="{p_id}" '+str+' amount_fixed="{p_amount_fixed}" p_min_amt="{p_min_amt}" p_max_amt="{p_max_amt}">{p_period}月</div>',true);
                    $('#periodList').html(html);
                    getFundList();
                }
            } else if (data.status == '5000') {
                falert(data.msg, '/user/mechanism');
            }
        }
    });  
}

function getFundList(){
    var amount_fixed = $('#periodList').find('.selectedNumber').attr('amount_fixed');
    var amt = parseFloat($('#periodList').find('.selectedNumber').attr('amt'));

    //console.log(amt);
    if(amount_fixed == '1' && amt > 0){
        $('#b_borrow_amount').val(amt).attr('readonly',true);
    }else if(amt > 0){
        $('#b_borrow_amount').val(amt);
    }
    var p_id = $('#periodList').find('.selectedNumber').attr('p_id');
    $('#p_id').val(p_id);
    var period = $('#periodList').find('.selectedNumber').attr('value');
    $('#b_period').val(period);
    if(period == ''){
        falert('请选择正确的课程');
        return false;
    }

    var datas = {
        interface:'product@fundList',
        period:period
    };
    var html = '';
    common.ajax({
        data: datas,
        success: function (data) {
            if (data.status == '2000') {
                if(data.result.length>1){
                    html += common.formatTemplate(data.result,'<div style="width:1.3rem" value="183" maxval="{fund_order_max_amt}" onclick="xzSelected(this,\'fundList\')">{fund_name}</div>',true);
                    $('#fundList').html(html);
                    $('#selectFund').hide();
                }else{
                    html = common.formatTemplate(data.result,'<div class="selectedNumber" value="183" maxval="{fund_order_max_amt}">{fund_name}</div>',true);
                    setTimeout(function(){
                        var fund_id = $('#fundList').find('.selectedNumber').attr('value');
                        $('#fund_id').val('183');
                    }, 200);
                    $('#fundList').html(html);
                    $('#selectFund').hide();
                }
            } else if (data.status == '5000') {
                falert(data.msg, '/user/mechanism');
            }
        }
    });  
}

function submitMsg() {
    var param = getRequest();
    var orderInfo = common.formatFormData('orderInfo');
    //console.log(orderInfo);
    if (!checkParams(orderInfo))
        return false;
    // var arr = ['1', '2', '3', '10'];
    var arr = ['1', '2', '3'];
    var daturm = [];
    var flag = true;
    var result = true;
    $.each(arr, function (i, o) {
        if($('#file' + o).val() == ''){
            flag = false;
            return false;
        }
        var file = [o, $('#file' + o).val()];
        daturm.push(file);
    });
    if(!flag){
        falert('请您上传资料');
        return false;
    }
    if($('#is_partner_k12').val() == '2'){
        result = common.checkForm().checkName($('#b_student_name').val(), function (result, error) {
            if (result == false) {
                falert(error);
                return false;
            }
        }).value;
    }

    var p_min_amt = parseFloat($('#periodList').find('.selectedNumber').attr('p_min_amt'));
    var p_max_amt = parseFloat($('#periodList').find('.selectedNumber').attr('p_max_amt'));
    if (parseFloat($('#b_borrow_amount').val()) <= 0) {
        falert('请输入正确的课程金额');
        return false;
    } else if (parseFloat($('#b_borrow_amount').val()) < p_min_amt) {
        falert('课程金额不能低于最小额度（'+parseInt(p_min_amt)+'）');
        return false;
    } else if (parseFloat($('#b_borrow_amount').val()) > p_max_amt) {
        $("#b_borrow_amount").val(p_max_amt);
        falert('课程金额超出了最大额度（'+parseInt(p_max_amt)+'）');
        return false;
    }

    if(result == true){
        var datas = new Object;
        datas.orderInfo = orderInfo;
        datas.daturmInfo = daturm;
        datas.order_num = param['order_num'];
        datas.interface = 'order@createOrder';
        datas.isInsurance = 0;
        if ($('#is_insurance').is(':checked')) {
            datas.isInsurance = 1;
        }
        // 可以传也可以不传
        datas.insuranceAmount = $('#insuranceAmount').text();
        common.ajax({
            data: datas,
            success: function (data) {
                if (data.status == '2000') {
                    //通话服务密码页面
                    //location.href = '/user/addyys';
                    //基本信息页面
                    //location.href = '/user/addmsg';
                    //跳转身份证信息页面
                    location.href = '/user/authform?b_id='+data.result.b_id;
                } else if (data.status == '5000') {
                    if(data.result.jumpUrl){
                        falert(data.msg,data.result.jumpUrl);
                    }else{
                        falert(data.msg);
                    }
                }
            }
        });
    }
}

function xzSelected(obj,id){
    var p_name = $('#productList').val();
    if(p_name == ''){
        falert('请选择正确的课程名称');
        return false;
    }
    $("#"+id+" div").removeClass("selectedNumber");
    $(obj).addClass("selectedNumber");
    if(id == 'periodList'){
        getFundList();
    }else if(id == 'fundList'){
        var fund_id = $('#'+id).find('.selectedNumber').attr('value');
        $('#fund_id').val(fund_id);
    }
}

function getRequest() {
    var url = location.search; //获取url中"?"符后的字串
    var theRequest = new Object();
    if(url.indexOf("?") != -1){
        var str = url.substr(1);
        strs = str.split("&");
        for(var i = 0; i < strs.length; i ++) {
            theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
        }
    }

    return theRequest;
}